package com.pz.art.service.impl;

import com.pz.art.service.UnitService;
import com.pz.art.domain.AssoMemberUnit;
import com.pz.art.mapper.UnitMapper;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.impl.SysUserServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.Validator;
import java.util.List;

@Service
@Primary
public class UnitServiceImpl implements UnitService {

    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired
    protected UnitMapper unitMapper;

    @Autowired
    protected SysUserMapper userMapper;

    @Autowired
    protected Validator validator;

    @Autowired
    private ISysConfigService configService;

    @Override
    public List<AssoMemberUnit> selectAllMember(AssoMemberUnit assoMemberUnit) {
        return unitMapper.selectAllMember(assoMemberUnit);
    }

    @Override
    public AssoMemberUnit selectMemberById(Integer id) {
        return unitMapper.selectMemberById(id);
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public String importUnit(List<AssoMemberUnit> unitList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(unitList) || unitList.size() == 0)
        {
            throw new ServiceException("导入会员单位数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (AssoMemberUnit memberUnit : unitList)
        {
            try
            {
                String password = configService.selectConfigByKey("sys.user.initPassword");
                SysUser user = new SysUser();
                user.setPassword(SecurityUtils.encryptPassword(password));
                user.setUserName(memberUnit.getPhone());
                user.setmarkers(2L);
                user.setPhonenumber(memberUnit.getPhone());
                user.setNickName(memberUnit.getPhone());
                user.setStatus("0");
                // 验证是否存在这个手机号

                SysUser u = userMapper.getUserByPhone(memberUnit.getPhone());
                AssoMemberUnit nu = unitMapper.selectAsooMemberUnitByPhone(memberUnit.getPhone());
                System.out.println(memberUnit.getPhone());
                System.out.println(u);
                System.out.println(StringUtils.isNull(u));
                if (StringUtils.isNull(u) && StringUtils.isNull(nu))
                {
                    BeanValidators.validateWithException(validator, memberUnit);
                    unitMapper.insertUnit(memberUnit);
                    user.setUnitId(memberUnit.getId());
                    BeanValidators.validateWithException(validator, user);
                    userMapper.insertUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
                }
                // 如果已经存在，则更新数据 功能暂时废弃
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 "  + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public int updateMember(AssoMemberUnit assoMemberUnit) {
        assoMemberUnit.setUpdate_time(DateUtils.getNowDate());
        assoMemberUnit.setMember_logo(assoMemberUnit.getMember_logo());
        assoMemberUnit.setMember_unit_name(assoMemberUnit.getMember_unit_name());
        assoMemberUnit.setMember_grade(assoMemberUnit.getMember_grade());
        assoMemberUnit.setContact(assoMemberUnit.getContact());
        assoMemberUnit.setMaturity_time(assoMemberUnit.getMaturity_time());
        return unitMapper.updateUnitMember(assoMemberUnit);
    }

    @Override
    public int deleteMemberById(Integer id,Integer status) {
        return unitMapper.updateUnitStatusToDie(id,status);
    }

    public void checkUserAllowed(SysUser user)
    {
        if (StringUtils.isNotNull(user.getUserId()) && user.isAdmin())
        {
            throw new ServiceException("不允许操作超级管理员用户");
        }
    }
}
